import {CloseCircleOutlined} from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Popover,
  Row,
  Select,
  Steps,
  Transfer,
  InputNumber,
  Table,
  message,
  Modal
} from 'antd';
import React, {useEffect, useState} from 'react';
import difference from 'lodash/difference';
import {FooterToolbar} from '@ant-design/pro-layout';
import styles from './style.less';
import TableForm from "@/pages/warehouse/stock-material/components/TableForm";
import {queryWarehouse} from "@/services/warehouse";
import {queryAccount, queryStaff} from "@/services/system";

// Customize Table Transfer
const TableTransfer = ({leftColumns, rightColumns, ...restProps}) => (
  <Transfer {...restProps} showSelectAll={false}>
    {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;

      const rowSelection = {
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .map(({processCode}) => processCode);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({processCode}, selected) {
          onItemSelect(processCode, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowKey={'processCode'}
          rowSelection={rowSelection}
          columns={columns}
          pagination={false}
          dataSource={filteredItems}
          size="small"
          style={{pointerEvents: listDisabled ? 'none' : null}}
          onRow={({processCode, disabled: itemDisabled}) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(processCode, !listSelectedKeys.includes(processCode));
            },
          })}
        />
      );
    }}
  </Transfer>
);

const mockData = [
  {
    processCode: 'PRO0001',
    processName: '开料',
    processType: '主工艺',
  },
  {
    processName: '图形电镀',
    processType: '主工艺',
    processCode: 'PRO0002',
  },
  {
    processName: '喷锡',
    processType: '主工艺',
    processCode: 'PRO0003',
  },
  {
    processName: '成形',
    processType: '主工艺',
    processCode: 'PRO0004',
  },
  {
    processName: '测试',
    processType: '主工艺',
    processCode: 'PRO0005',
  },
  {
    processName: 'FQC',
    processType: '主工艺',
    processCode: 'PRO0006',
  },
  {
    processName: '检测',
    processType: '检测工艺',
    processCode: 'PRO0007',
  },
  {
    processName: '入库',
    processType: '其他',
    processCode: 'PRO0008',
  },
  {
    processName: '内层线路',
    processType: '主工艺',
    processCode: 'PRO0009',
  },
  {
    processName: '内层检验',
    processType: '检测工艺',
    processCode: 'PRO0010',
  },
  {
    processName: '层压',
    processType: '其他',
    processCode: 'PRO0011',
  },
  {
    processName: '沉铜板电',
    processType: '其他',
    processCode: 'PRO0012',
  }
]

const originTargetKeys = mockData.filter(item => +item.processCode % 3 > 1).map(item => item.processCode);


const {Option} = Select;
const {RangePicker} = DatePicker;
const fieldLabels = {
  warehouseCode: {
    label: '仓库编码',
    code: 'warehouseCode',
  },
  warehouseId: {
    label: '仓库编码',
    code: 'warehouseId',
  },
  warehouseName: {
    label: '仓库名称',
    code: 'warehouseName',
  },
  applyBy: {
    label: '领用人',
    code: 'applyBy',
  },
  num: {
    label: '出库数量',
    code: 'num'
  },
  remark: {
    label: '备注',
    code: 'remark',
  },
  materials: {
    label: '物料',
    code: 'materials',
  }
};

const StockMaterialForm = (props, {submitting, dispatch}) => {
  const {visible, onSubmit, materialData, type} = props;
  //console.log((materialData)
  const {TextArea} = Input;
  const {Step} = Steps;
  const [form] = Form.useForm();
  const [error, setError] = useState([]);
  const [warehouseData, setWarehouseData] = useState([]);
  const [applyData, setApplyData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [isProcessModalVisible, setIsProcessModalVisible] = useState(false);
  const [targetKeys, setTargetKeys] = useState(originTargetKeys);
  const [targetData, setTargetData] = useState([]);

  useEffect(()=>{
    queryWarehouse({pageNum: 1, pageSize: 99999}).then(res=>{
      if(res && res.status === '0') {
        setWarehouseData(res.result.records)
      }
    })
  },[])

  const getErrorInfo = (errors) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }

    const scrollToField = (fieldKey) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);

      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    //console.log((errors)
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }

      const key = err.name[0];
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon}/>
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key].label}</div>
        </li>
      );
    });
    //console.log((errorList)
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode;
            }

            return trigger;
          }}
        >
          <CloseCircleOutlined/>
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = (values) => {
    if (values.materials !== undefined && values.materials.length > 0) {
      let isEmpty = false
      values.materials.forEach(m=>{
        if (!m) {
          isEmpty = true;
          return;
        }
      })
      if (!isEmpty) {
        onSubmit(values)
      }else {
        message.error("请选择物料并选择数量")
      }
    }else {
      message.error("请选择物料并选择数量")
    }
  };

  const onFinishFailed = (errorInfo) => {
    //console.log((errorInfo)
    setError(errorInfo.errorFields);
  };

  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys)
    //console.log((nextTargetKeys)
    const targetDatas = mockData.filter((item)=>{
      let isExist;
      for (let key of nextTargetKeys) {
        if (item.processCode === key) {
          isExist = true;
          break;
        }
      }
      return isExist
    })
    setTargetData(targetDatas)
  }

  const handleProcessOk = ()=>{
    setIsProcessModalVisible(false);
  }

  const handleProcessCancel = ()=>{
    setIsProcessModalVisible(false);
  }

  const onWarehouseChange = (v, o) =>{
    form.setFieldsValue({
      warehouseId : v
    })
  }

  const onApplyBySearch = (v)=>{
    if (v) {
      queryStaff({
        staffName: v,
        pageSize: 99999,
        pageNum: 1,
        staffStatus: 1
      }).then(res=>{
        if(res && res.status === '0') {
          setApplyData(res.result.records)
        }
      })
    }
  }

  return (
    <div className={'product-form'}>
      {
        type === 1? <Form
          form={form}
          layout="vertical"
          hideRequiredMark
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <>
            <Card title="基本信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseName.label}
                    name={fieldLabels.warehouseName.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseName.label}`,
                      },
                    ]}
                  >
                    <Select onChange={(v, o)=>onWarehouseChange(v, o)}>
                      {warehouseData.map(item=>{
                        return <Option value={item.warehouseId} key={item.warehouseCode}>{item.warehouseName}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseId.label}
                    name={fieldLabels.warehouseId.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseId.label}`,
                      },
                    ]}
                  >
                    <Input disabled={true}/>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.remark.label}
                    name={fieldLabels.remark.code}
                  >
                    <TextArea placeholder={`请输入${fieldLabels.remark.label}`}/>
                  </Form.Item>
                </Col>
              </Row>
            </Card>
            <Card title="选择物料" bordered={false}>
              <Form.Item name="materials">
                <TableForm disabled={type === 2} onChange={(v)=>{console.log((v))}} />
              </Form.Item>
            </Card>
          </>
          <FooterToolbar>
            {getErrorInfo(error)}
            <Button type="primary" onClick={props.onCancel.bind(this, false)}>
              返回
            </Button>
            <Button type="primary" onClick={() => form?.submit()} >
              提交
            </Button>
          </FooterToolbar>
        </Form>:<Form
          form={form}
          layout="vertical"
          initialValues={{
            materials: [materialData],
            warehouseId: materialData.warehouseId,
            warehouseName: materialData.warehouseName,
          }}
          hideRequiredMark
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <>
            <Card title="基本信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseName.label}
                    name={fieldLabels.warehouseName.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseName.label}`,
                      },
                    ]}
                  >
                    <Select disabled={true} onChange={(v, o)=>onWarehouseChange(v, o)}>
                      {warehouseData.map(item=>{
                        return <Option value={item.warehouseId} key={item.warehouseCode}>{item.warehouseName}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseId.label}
                    name={fieldLabels.warehouseId.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseId.label}`,
                      },
                    ]}
                  >
                    <Input disabled={true}/>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16} style={{display: type === 2? 'block': 'none'}}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.num.label}
                    name={fieldLabels.num.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.num.label}`,
                      },
                      {
                        pattern: /^[1-9]\d*$/,
                        message: '只能输入整数'
                      }
                    ]}
                  >
                    <InputNumber max={materialData.num} min={1} placeholder={`请输入${fieldLabels.num.label}`} style={{width: '100%'}}/>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.applyBy.label}
                    name={fieldLabels.applyBy.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.applyBy.label}`,
                      },
                    ]}
                  >
                    <Select
                      showSearch
                      defaultActiveFirstOption={false}
                      showArrow={false}
                      filterOption={false}
                      onSearch={(v)=>onApplyBySearch(v)}
                      notFoundContent={null}
                    >
                      {applyData.map(item=>{
                        return <Option value={item.staffId} key={item.staffId}>{item.realName}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.remark.label}
                    name={fieldLabels.remark.code}
                  >
                    <TextArea placeholder={`请输入${fieldLabels.remark.label}`}/>
                  </Form.Item>
                </Col>
              </Row>
            </Card>
            <Card title="选择物料" bordered={false}>
              <Form.Item name="materials">
                <TableForm disabled={type === 2} onChange={(v)=>{console.log((v))}} />
              </Form.Item>
            </Card>
          </>
          <FooterToolbar>
            {getErrorInfo(error)}
            <Button type="primary" onClick={props.onCancel.bind(this, false)}>
              返回
            </Button>
            <Button type="primary" onClick={() => {

              form?.submit()
            }} >
              提交
            </Button>
          </FooterToolbar>
        </Form>
      }


    </div>
  );
};

// export default connect(({ loading }) => ({
//   submitting: loading.effects['productForm/submitAdvancedForm'],
// }))(ProductForm);
export default StockMaterialForm;
